<template>
  <div class="procure-plan-wrap">
    <!-- 查询表单 -->
    <el-card class="mb16">
      <el-form :inline="true" :model="queryForm" class="query-form" >
        <el-form-item label="采购单号" prop="procureId">
          <el-input
              v-model="queryForm.procureId"
              placeholder="请输入采购单号"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品ID" prop="productId">
          <el-input-number
              v-model="queryForm.productId"
              :min="1"
              placeholder="请输入商品ID"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
              v-model="queryForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
          >
            <el-option label="未审核" value="0" />
            <el-option label="已审核" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
              v-model="queryForm.type"
              placeholder="请选择类型"
              clearable
              style="width: 200px"
          >
            <el-option label="成品" value="1" />
            <el-option label="次品" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :icon="Search">查询</el-button>
          <el-button @click="resetQuery" :icon="RefreshRight">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏与分页 -->
    <el-row justify="space-between" align="middle" class="mb16">
      <el-button type="primary" :icon="Plus" @click="openAdd">新增计划</el-button>
      <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="size"
          v-model:current-page="page"
          @current-change="loadData"
          class="pagination"
      />
    </el-row>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        border
        align="center"
        header-align="center"
        :cell-style="{ padding: '12px 0' }"
    >
      <el-table-column prop="procureId" label="采购单号" width="200" />
      <el-table-column prop="productId" label="商品名称" width="150">
        <template #default="{ row }">
          {{ getProOpts.find(i => i.value === row.productId)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="num" label="数量" width="120" />
      <el-table-column prop="price" label="单价(元)" width="120" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          {{ typeMap[row.type] }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="140">
        <template #default="{ row }">
          <el-tag :type="statusColor(row.status)" effect="dark">
            {{ statusMap[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="160" fixed="right">
        <template #default="{ row }">
          <!-- 已审核的记录禁用编辑按钮 -->
          <el-button
              size="small"
              @click="openEdit(row)"
              :disabled="row.status === 1"
              :title="row.status === 1 ? '已审核记录不能编辑' : ''"
          >
            编辑
          </el-button>

          <!-- 未审核的记录显示审核按钮 -->
          <el-button
              size="small"
              type="success"
              @click="handleAudit(row)"
              v-if="row.status === 0"
          >
            审核
          </el-button>

          <el-popconfirm title="确定删除?" @confirm="handleDelete(row.procureId)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑抽屉 -->
    <el-drawer
        v-model="drawer"
        :title="isAdd ? '新增采购计划' : '编辑采购计划'"
        direction="rtl"
        size="500px"
        destroy-on-close
        @closed="resetForm"
    >
      <el-form
          ref="formRef"
          :model="form"
          label-width="100px"
          :rules="rules"
          class="drawer-form"
      >
        <el-form-item label="采购单号" prop="procureId">
          <el-input v-model="form.procureId" placeholder="请输入采购单号" />
        </el-form-item>
        <el-form-item label="商品编号" prop="productId">
          <el-input-number
              v-model="form.productId"
              :min="1"
              style="width:100%"
              placeholder="请输入商品编号"
          />
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number
              v-model="form.num"
              :min="0.01"
              :precision="2"
              style="width:100%"
              placeholder="请输入数量"
          />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number
              v-model="form.price"
              :min="0.01"
              :precision="2"
              style="width:100%"
              placeholder="请输入单价"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="1">成品</el-radio>
            <el-radio label="2">次品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">未审核</el-radio>
            <el-radio :label="1">已审核</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { Plus, Search, RefreshRight, Edit, Delete } from '@element-plus/icons-vue'
import {
  findAllPlan,
  addPlan,
  updatePlan,
  getProOpts,
  deletePlan,
  findPlanByCondition  // 新增：导入条件查询接口
} from '../../api/wms.js'

const defaultForm = () => ({
  procureId: '',
  productId: null,
  num: null,
  price: null,
  type: '1',
  status: 0,
  orderId: ''
})

export default {
  name: 'ProcurePlan',
  components: { Plus, Search, RefreshRight, Edit, Delete },
  data() {
    return {
      loading: false,
      tableData: [],
      total: 0,
      page: 1,
      size: 8,  // 调整每页显示数量
      drawer: false,
      isAdd: true,
      form: defaultForm(),
      getProOpts: [],
      // 查询表单数据
      queryForm: {
        procureId: '',
        productId: null,
        status: null,
        type: ''
      },
      // 表单验证规则
      rules: {
        procureId: [
          { required: true, message: '请输入采购单号', trigger: 'blur' }
        ],
        productId: [
          { required: true, message: '请输入商品编号', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '数量必须大于0', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入单价', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
        ]
      },
      typeMap: { '1': '成品', '2': '次品' },
      statusMap: { 0: '未审核', 1: '已审核' }
    }
  },
  mounted() {
    this.loadSelect()
    this.loadData()
  },
  methods: {
    async handleAudit(row) {
      try {
        // 创建一个新对象，仅修改状态字段
        const updatedPlan = {
          ...row,
          status: 1 // 将状态改为已审核
        };
        await updatePlan(updatedPlan);
        ElMessage.success('审核成功');
        this.loadData(); // 重新加载数据
      } catch (error) {
        ElMessage.error('审核失败');
        console.error(error);
      }
    },
    async loadSelect() {
      const p = await getProOpts()
      this.getProOpts = p || []
    },
    async loadData() {
      this.loading = true
      try {
        // 使用条件查询接口
        const res = await findPlanByCondition(this.queryForm)
        const list = res?.data?.data || res?.data || []
        this.tableData = list.slice((this.page - 1) * this.size, this.page * this.size)
        this.total = list.length
      } catch (error) {
        ElMessage.error('数据加载失败')
      } finally {
        this.loading = false
      }
    },
    statusColor(st) {
      return ['warning', 'success'][st] || 'info'
    },
    openAdd() {
      this.isAdd = true
      this.drawer = true
    },
    openEdit(row) {
      this.isAdd = false
      this.form = { ...row }
      this.drawer = true
    },
    async handleDelete(id) {
      try {
        await deletePlan(id)
        ElMessage.success('删除成功')
        this.loadData()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    },
    async submit() {
      try {
        await this.$refs.formRef.validate()  // 表单验证
        const api = this.isAdd ? addPlan : updatePlan
        await api(this.form)
        ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
        this.drawer = false
        this.loadData()
      } catch (error) {
        if (error.name !== 'Error') return  // 忽略验证失败的错误
        ElMessage.error(this.isAdd ? '新增失败' : '修改失败')
      }
    },
    resetForm() {
      this.$refs.formRef?.resetFields()
      this.form = defaultForm()
    },
    // 查询处理
    handleQuery() {
      this.page = 1  // 重置页码
      this.loadData()
    },
    // 重置查询
    resetQuery() {
      this.queryForm = {
        procureId: '',
        productId: null,
        status: null,
        type: ''
      }
      this.page = 1
      this.loadData()
    }
  }
}
</script>

<style scoped>
.procure-plan-wrap {
  padding: 20px;
  background: var(--el-bg-color);
  min-height: 100%;
}
.mb16 {
  margin-bottom: 16px;
}
.query-form {
  padding: 10px 0;
}
.pagination {
  margin-top: 10px;
}
.drawer-form {
  margin-top: 20px;
}
:deep(.el-form-item) {
  margin-bottom: 18px;
}
:deep(.el-tag) {
  padding: 4px 8px;
  border-radius: 4px;
}
</style>